#!/usr/bin/python
# Filename: mjs_conf.py

import os
import json
import logging
import socket
import fcntl
import struct
from mjs_public import singleton

class MjsConf(singleton.Singleton):
    is_debug = True
    host = ""
    mjc_port = 0
    mjw_port = 0
    file_server_port = 0
    mjc_max = 0
    mjw_max = 0
    file_server_max = 0
    db_user = ""
    db_passwd = ""
    db_name = ""

    def load(self, path):
        config_file = open(path, "r")
        content = config_file.read()

        try:
            config_dict = json.loads(content)
        except Exception, e:
            logging.error("read config file:'%s' failed: %s" % (path, e))
            return False

        if config_dict['debug'] == "yes":
            self.is_debug = True
            logging.info("debug runing")
            self.host = config_dict['local']
            logging.info("local host = %s", self.host)
        else:
            self.is_debug = False
            try:
                # self.host = socket.gethostbyname(config_dict['domain'])
                self.host = config_dict['eth0']
                logging.info("local host = %s", self.host)
            except Exception, e:
                logging.error("get interface = '%s' ip address failed: %s" % (config_dict['eth0'], e))
                return False

        self.mjc_port = config_dict['mjc_server_port']
        logging.info("mjc_server_port = %d" % self.mjc_port)

        self.mjw_port = config_dict['mjw_server_port']
        logging.info("mjw_server_port = %d" % self.mjw_port)

        self.file_server_port = config_dict['file_server_port']
        logging.info("file_server_port = %d" % self.file_server_port)        

        self.mjc_max = config_dict['mjc_con_max']
        logging.info("mjc_con_max = %d" % self.mjc_max)

        self.mjw_max = config_dict['mjw_con_max']
        logging.info("mjw_con_max = %d" % self.mjw_max)

        self.file_con_max = config_dict['file_con_max']
        logging.info("file_con_max = %d" % self.file_server_max)   

        self.db_user = config_dict['db_user']
        self.db_name = config_dict['db_name']
        self.db_passwd = config_dict['db_passwd']

        return True
    pass

    def __get_local_ip(self, ifname):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        ip = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24])
        return ip